package com.yadong.smarthome2.protocol2.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.text.TextUtils;

import com.yadong.smarthome2.protocol2.Protocol;
import com.yadong.smarthome2.protocol2.RequestProtocol.Request;
import com.yadong.smarthome2.protocol2.ResultProtocol.Function;
import com.yadong.smarthome2.protocol2.ResultProtocol.Result;

public abstract class FunctionManager {
    private HashMap<Function, FunctionRunable> mFunctions =
            createAllFunctions();

    protected abstract HashMap<Function, FunctionRunable> createAllFunctions();

    /**
     * Check the request is a function Request or not.
     * @param request
     * @return
     */
    public final boolean isFunctionRequest(Request request) {
        String requestTag = request.getTag();
        if (!TextUtils.isEmpty(requestTag)) {
            for (Function function : mFunctions.keySet()) {
                if (requestTag.equals(function.getCode())) {
                    return true;
                }
            }
        }
        return false;
    }

    public List<Function> getAllFunctions() {
        ArrayList<Function> functions = new ArrayList<Function>();
        functions.addAll(mFunctions.keySet());
        return functions;
    }

    public final Result doFunction(Request request) {
        String requestTag = request.getTag();
        Result.Builder resultBuilder = Result.newBuilder();
        resultBuilder.setTag(request.getTag());
        resultBuilder.setTime(request.getTime());
        boolean success = false;
        if (!TextUtils.isEmpty(requestTag)) {
            for (Function function : mFunctions.keySet()) {
                if (requestTag.equals(function.getCode())) {
                    FunctionRunable runable = mFunctions.get(function);
                    //TODO 這裡要創建Result..的內容
                    runable.runInternal(request, resultBuilder);
                    success = true;
                }
            }
        }
        if (!success) {
            resultBuilder.addResult(Protocol.RESULT_FAILD);
        }
        return resultBuilder.build();
    }

}
